package com.gitee.feizns.quickstart.ding.talk.api.top.api.smart.device.device;

import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiSmartdeviceDeviceQuerylistRequest;
import com.dingtalk.api.response.OapiSmartdeviceDeviceQuerylistResponse;
import com.gitee.feizns.quickstart.ding.talk.utils.Utils;
import lombok.SneakyThrows;

import java.util.ArrayList;
import java.util.List;

/**
 * 接口路径：<a href="https://open.dingtalk.com/document/orgapp/intelligent-hardware-list-query">绑定设备（/topapi/smartdevice/device/querylist）</a>
 * @link <a href="https://open.dingtalk.com/document/orgapp/intelligent-hardware-list-query">服务端API 智能硬件 设备管理 查询设备列表</a>
 * @author feizns
 * @since 2024/3/18
 */
public class QueryList {

    /**
     * 查询设备列表
     * @param vo {@link OapiSmartdeviceDeviceQuerylistRequest.PageQueryVo}
     * @param accessToken {@link <a href="https://open.dingtalk.com/document/orgapp/authorization-overview">获取访问凭据</a>}
     */
    @SneakyThrows
    public static OapiSmartdeviceDeviceQuerylistResponse.PageResult execute(String accessToken, OapiSmartdeviceDeviceQuerylistRequest.PageQueryVo vo) {
        DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/smartdevice/device/querylist");
        OapiSmartdeviceDeviceQuerylistRequest req = new OapiSmartdeviceDeviceQuerylistRequest();
        req.setPageQueryVo(vo);
        OapiSmartdeviceDeviceQuerylistResponse resp = client.execute(req, accessToken);
        return Utils.ifErrorThrow(resp).getResult();
    }

    /**
     * 查询所有设备列表
     * @param pk 产品唯一标识
     * @param accessToken 访问凭据
     * @return {@link List}<{@link OapiSmartdeviceDeviceQuerylistResponse.DeviceDetailVO}>
     */
    @SneakyThrows
    public static List<OapiSmartdeviceDeviceQuerylistResponse.DeviceDetailVO> execute(String accessToken, String pk) {
        OapiSmartdeviceDeviceQuerylistRequest.PageQueryVo vo = new OapiSmartdeviceDeviceQuerylistRequest.PageQueryVo();
        vo.setPk(pk);
        vo.setSize(20L);
        Long cursor = 0L;
        OapiSmartdeviceDeviceQuerylistResponse.PageResult result;
        List<OapiSmartdeviceDeviceQuerylistResponse.DeviceDetailVO> deviceDetailVOS = new ArrayList<>();
        do {
            vo.setCursor(cursor);
            result = execute(accessToken, vo);
            cursor = result.getNextCursor();
            deviceDetailVOS.addAll(result.getList());
        } while ( result.getHasMore() );
        return deviceDetailVOS;
    }

}
